package excelRepo

import (
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/go-ini/ini"
	"github.com/sirupsen/logrus"
	"github.com/xuri/excelize/v2"
)

// 创建一个文件夹  保存excel文件 ；判断result文件夹是否存在
func MakeDir(directoryName string) {
	if _, err := os.Stat(directoryName); os.IsNotExist(err) {
		// 不存在则创建一个result空文件夹
		os.Mkdir(directoryName, os.ModePerm)
	}
}

// 读取excel文档
func ReadExcel() {
	// 加载ini文件
	cfgs, _ := ini.Load("./excelRepo/score_details_2_excel.ini")
	str := cfgs.Section("huahua").Key("tmplExcelName").Value()
	fmt.Println(str)
	f, err := excelize.OpenFile(fmt.Sprintf(`./tmpl/%s`, cfgs.Section("huahua").Key("tmplExcelName").Value()))
	if err != nil {
		logrus.Info("OpenFile error:", err.Error())
		return
	}

	// 关闭excel文档
	defer func() {
		if err := f.Close(); err != nil {
			logrus.Info("f.Close() error:", err.Error())

		}
	}()

	// 获取 Sheet1 上所有单元格
	rows, err := f.GetRows(cfgs.Section("huahua").Key("sheetName").Value())
	if err != nil {
		logrus.Info("f.GetRows error:", err.Error())
		return
	}
	fmt.Println("表格数据行：", len(rows))
	// fmt.Println(rows)

	// 新建excel
	newf := excelize.NewFile()
	defer func() {
		if err := newf.Close(); err != nil {
			logrus.Info("newf file Close error: ", err.Error())
		}
	}()

	// newfCurrentRow := 0

	// 最大列数
	colCount, err := strconv.Atoi(cfgs.Section("huahua").Key("colCount").Value())
	if err != nil {
		logrus.Info("strconv.Atoi colCount error:", err.Error())
		return
	}
	// 总行数
	// maxRowNum := len(rows)
	// 起始行
	startRowNum := 0
	// 列名：表头
	var colNameArr []string
	rowCount := 0 //每个学生分组行数
	for rowIndex, row := range rows {
		if len(row) <= 1 {
			continue
		}
		if len(colNameArr) == 0 {
			startRowNum = rowIndex + 1
			colNameArr = row
			rowCount = len(colNameArr) / colCount
			if len(colNameArr)%colCount != 0 {
				rowCount++
			}
			continue
		}
		// fmt.Println("startRowNum", startRowNum)

		studentNo := rowIndex - startRowNum                //第几名学生
		insertTitle(newf, colNameArr, rowCount, studentNo) //插入表头
		insertScore(newf, row, rowCount, studentNo)        //插入数据

	}

	// 设置样式
	SetCss(newf, 0, (len(rows)-startRowNum)*rowCount*2, map[string]string{"Horizontal": "center"})

	// 插入空行
	insertEmptRow(newf, len(rows)-startRowNum, rowCount)

	// newfRows, err := newf.GetRows("Sheet1")
	// if err != nil {
	// 	logrus.Info("newf.GetRows error:", err.Error())
	// 	return
	// }
	// fmt.Println(newfRows)
	// // 根据指定路径保存文件,文件名待配置
	now := time.Now().Format("20060102")
	fileName := fmt.Sprintf(`./result/%s-%s`, now, cfgs.Section("huahua").Key("fileName").Value())
	fmt.Println("fileName: ", fileName)
	if err := newf.SaveAs(fileName); err != nil {
		logrus.Info("f.SaveAs error: ", err.Error())
	}
}

// 插入表头  rowCount 单人占用行数
func insertTitle(newf *excelize.File, colNameArr []string, rowCount int, studentNo int) {
	cfgs, _ := ini.Load("./excelRepo/score_details_2_excel.ini")
	// 最大列数
	colCount, err := strconv.Atoi(cfgs.Section("huahua").Key("colCount").Value())
	if err != nil {
		logrus.Info("strconv.Atoi colCount error:", err.Error())
		return
	}
	for i := 0; i < rowCount; i++ {
		end := (i + 1) * colCount
		if end > len(colNameArr) {
			end = len(colNameArr)
		}
		slice := colNameArr[i*colCount : end]
		// fmt.Println(i*colCount, end)
		// fmt.Println(slice)

		newf.SetSheetRow("Sheet1", fmt.Sprintf("A%d", studentNo*rowCount*2+i*2+1), &slice)
		// 获取 Sheet1 上所有单元格

	}
}

// 插入分值
func insertScore(newf *excelize.File, row []string, rowCount int, studentNo int) {
	cfgs, _ := ini.Load("./excelRepo/score_details_2_excel.ini")
	// 最大列数
	colCount, err := strconv.Atoi(cfgs.Section("huahua").Key("colCount").Value())
	if err != nil {
		logrus.Info("strconv.Atoi colCount error:", err.Error())
		return
	}
	for i := 0; i < rowCount; i++ {
		end := (i + 1) * colCount
		if end > len(row) {
			end = len(row)
		}
		slice := row[i*colCount : end]
		// fmt.Println(i*colCount, end)
		// fmt.Println(slice)

		newf.SetSheetRow("Sheet1", fmt.Sprintf("A%d", studentNo*rowCount*2+i*2+2), &slice)
		// 获取 Sheet1 上所有单元格

	}

}

// 分组插入空行 studentSum:学生总数   rowCount*2 单学生占用行
func insertEmptRow(newf *excelize.File, studentSum int, rowCount int) {
	// fmt.Println(newf)
	for i := 1; i <= studentSum; i++ {
		rowNum := i*rowCount*2 + i
		newf.InsertRows("Sheet1", rowNum, 1)
	}

}

type rowData struct {
	investorid   string
	investorname string
	product      string
	longpos      int
	shortpos     int
}

// 插入excel数据
func InsertData() {
	allData := []rowData{
		{
			investorid:   "11",
			investorname: "test1",
			product:      "pro1",
			longpos:      1,
			shortpos:     2,
		},
		{
			investorid:   "22",
			investorname: "test2",
			product:      "pro2",
			longpos:      -1,
			shortpos:     -2,
		},
		{
			investorid:   "33",
			investorname: "test3",
			product:      "pro3",
			longpos:      33,
			shortpos:     44,
		},
	}
	// 备注信息
	remarkData := []string{
		"大连jd买入交割货款冻结时间为01月30日14：30分。关注客户的交月份合约的跨期套利特仓。交割配对后，涉及组合保证金的重新计算和买近卖近标准仓单过期的风险。豆1、豆2、豆柏、豆油、棕脚油须要客户提供合法有效的能够接收或者开具增值税发票的资质证明。液化石油气和苯乙烯须要提交合法有效的苯乙烯生产、经营或使用的资质证明。",
		"	买方客户提出的交割宜向供交易所参考，实际获得的电子仓单将按照交易规则分配，可能存在不符合客户提交意向的情况。",
	}
	// fmt.Println(allData)

	// 加载ini文件
	cfgs, _ := ini.Load("./excelRepo/score_details_2_excel.ini")
	f, err := excelize.OpenFile(fmt.Sprintf(`./tmpl/%s`, cfgs.Section("emailConfig").Key("tmplExcelName").Value()))
	if err != nil {
		logrus.Info("OpenFile error:", err.Error())
		return
	}

	// 关闭excel文档
	defer func() {
		if err := f.Close(); err != nil {
			logrus.Info("f.Close() error:", err.Error())

		}
	}()

	// 获取 Sheet1 上所有单元格
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		logrus.Info("f.GetRows error:", err.Error())
		return
	}

	// 表头行数
	headLen := len(rows)
	fmt.Println("表格数据行：", headLen)

	for index, row := range allData {

		// fmt.Println(row)
		rowIdx := strconv.Itoa(headLen + index + 1)
		f.SetCellValue("Sheet1", "A"+rowIdx, index+1)
		f.SetCellValue("Sheet1", "B"+rowIdx, row.investorid)
		f.SetCellValue("Sheet1", "C"+rowIdx, row.investorname)
		f.SetCellValue("Sheet1", "D"+rowIdx, row.product)
		f.SetCellValue("Sheet1", "E"+rowIdx, row.longpos)
		f.SetCellValue("Sheet1", "F"+rowIdx, row.shortpos)
	}
	// 设置样式
	SetCss(f, len(rows), len(allData), map[string]string{"Horizontal": "center"})

	// 插入备注信息
	InsertRemarkData(f, remarkData)

	// 根据指定路径保存文件,文件名待配置
	now := time.Now().Format("20060102")
	fileName := fmt.Sprintf(`./result/%s-%s`, now, cfgs.Section("emailConfig").Key("fileName").Value())
	fmt.Println("fileName: ", fileName)
	if err := f.SaveAs(fileName); err != nil {
		logrus.Info("f.SaveAs error: ", err.Error())
	}

}

// 插入备注信息
func InsertRemarkData(f *excelize.File, remarkData []string) {
	// 再获取一次 方便插入备注信息
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		logrus.Info("f.GetRows error 2 :", err.Error())
		return
	}
	// 已有数据行数
	rowCount := len(rows)
	fmt.Println("已有数据行数 rowCount:", rowCount)

	for index, rowData := range remarkData {
		// fmt.Println(index, rowData)
		rowId := rowCount + index + 1
		rowIdx := strconv.Itoa(rowId)
		f.MergeCell("Sheet1", "B"+rowIdx, "F"+rowIdx)
		f.SetRowHeight("Sheet1", rowId, 50)

		f.SetCellValue("Sheet1", "A"+rowIdx, index+1)
		f.SetCellValue("Sheet1", "B"+rowIdx, rowData)
	}
	// 设置样式
	SetCss(f, len(rows), len(remarkData), map[string]string{"WrapText": "true"})
}

// 设置单元格样式  hLen :start   vLen : end  代码内+1了
func SetCss(f *excelize.File, hLen int, vLen int, alignmentMap map[string]string) {
	fmt.Println("start setCss")
	cfgs, _ := ini.Load("./excelRepo/score_details_2_excel.ini")
	// 最大列数
	colCount, err := strconv.Atoi(cfgs.Section("huahua").Key("colCount").Value())
	if err != nil {
		logrus.Info("strconv.Atoi colCount error:", err.Error())
		return
	}

	// 列名
	colName, err := excelize.ColumnNumberToName(colCount)
	if err != nil {
		logrus.Info("sexcelize.ColumnNumberToName error:", err.Error())
		return
	}

	alignment := &excelize.Alignment{}
	for key, value := range alignmentMap {
		switch key {
		case "Horizontal":
			alignment.Horizontal = value
		case "Indent":
			indent, err := strconv.Atoi(value)
			if err != nil {
				logrus.Info("strconv.Atoi error: ", err.Error())
			}
			alignment.Indent = indent
		case "JustifyLastLine":
			alignment.JustifyLastLine = value == "true"
		case "ReadingOrder":
			readingOrder, err := strconv.Atoi(value)
			if err != nil {
				logrus.Info("strconv.Atoi readingOrder error: ", err.Error())
			}
			alignment.ReadingOrder = uint64(readingOrder)
		case "RelativeIndent":
			relativeIndent, err := strconv.Atoi(value)
			if err != nil {
				logrus.Info("strconv.Atoi RelativeIndent error: ", err.Error())
			}
			alignment.RelativeIndent = relativeIndent
		case "ShrinkToFit":
			alignment.ShrinkToFit = value == "true"
		case "TextRotation":
			textRotation, err := strconv.Atoi(value)
			if err != nil {
				logrus.Info("strconv.Atoi error: ", err.Error())
			}
			alignment.TextRotation = textRotation
		case "Vertical":
			alignment.Vertical = value
		case "WrapText":
			alignment.WrapText = value == "true"
		default:
			logrus.Info("Unknown alignment key")
		}
	}

	style, err := f.NewStyle(&excelize.Style{
		Border: []excelize.Border{
			{Type: "left", Color: "000000", Style: 1},
			{Type: "top", Color: "000000", Style: 1},
			{Type: "bottom", Color: "000000", Style: 1},
			{Type: "right", Color: "000000", Style: 1},
		},
		Alignment: alignment,
	})
	if err != nil {
		logrus.Info("f.NewStyle error: ", err.Error())

	}

	styleBold, err := f.NewStyle(&excelize.Style{
		Border: []excelize.Border{
			{Type: "left", Color: "000000", Style: 1},
			{Type: "top", Color: "000000", Style: 1},
			{Type: "bottom", Color: "000000", Style: 1},
			{Type: "right", Color: "000000", Style: 1},
		},
		Alignment: alignment,
		Font: &excelize.Font{
			Bold: true,
		},
	})
	if err != nil {
		logrus.Info("f.NewStyle error: ", err.Error())

	}

	// 获取 Sheet1 上所有单元格
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		logrus.Info("f.GetRows error:", err.Error())
		return
	}

	rowsCount := len(rows)

	for i := 1; i <= rowsCount; i++ {
		if i%2 == 0 {
			err = f.SetCellStyle("Sheet1", "A"+strconv.Itoa(i), colName+strconv.Itoa(i), style)
		} else {
			err = f.SetCellStyle("Sheet1", "A"+strconv.Itoa(i), colName+strconv.Itoa(i), styleBold)

		}
	}

	// err = f.SetCellStyle("Sheet1", "A"+strconv.Itoa(hLen+1), colName+strconv.Itoa(hLen+vLen), style)
	if err != nil {
		fmt.Println(err)
		logrus.Info("f.SetCellStyle error: ", err.Error())

	}
}
